﻿using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Corina.Converters.Silverlight
{
    public class UrlToImageConverter : IValueConverter
    {
        ManualResetEvent waitHandle = new ManualResetEvent(false);

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }

            string webServiceAddress = Application.Current.IsRunningOutOfBrowser ? "http://www.byshuju.cn/" : Application.Current.Resources["WebServiceAddress"] as string;
            
            BitmapImage image = new BitmapImage();

            string url = string.Format("{3}loadfile.aspx?f={0}&n={1}&g={2}", parameter, value, System.Guid.NewGuid(), webServiceAddress);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";

            IAsyncResult async = (IAsyncResult)request.BeginGetResponse((IAsyncResult result) =>
            {
                try
                {
                    HttpWebRequest webRequest = result.AsyncState as HttpWebRequest;
                    HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(result);
                    Stream streamResult = webResponse.GetResponseStream();

                    System.Diagnostics.Debug.WriteLine(streamResult.Length);

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        image.SetSource(streamResult);
                    });

                    waitHandle.Set();
                }
                catch { }

            }, request);

            waitHandle.WaitOne(1);

            return image;
        }

        private BitmapImage GetBitmapImage(string url)
        {
            WebClient client = new WebClient();

            BitmapImage image = new BitmapImage();

            client.OpenReadCompleted += (s, e) =>
            {
                image.SetSource(e.Result);
            };

            return image;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
